#!/usr/bin/env node

import { LocalRepository } from './dist/local-repository.js';
import { ClassFinder } from './dist/class-finder.js';
import { JavaDecompiler } from './dist/decompiler.js';

async function testSearchAuditDomain() {
  const classFinder = new ClassFinder();
  const localRepository = new LocalRepository(classFinder);
  const decompiler = new JavaDecompiler();
  
  // Set the repository path
  const repoPath = '/mnt/d/mavenrepository';
  localRepository.setLocalRepositoryPath(repoPath);
  
  console.log(`Searching for AuditDomain class in repository: ${repoPath}`);
  
  try {
    // First, check if the repository directory exists
    console.log('Checking repository directory...');
    
    // Scan all local artifacts
    console.log('Scanning local repository...');
    const allArtifacts = await localRepository.scanLocalRepository();
    console.log(`Found ${allArtifacts.length} artifacts in local repository`);
    
    if (allArtifacts.length === 0) {
      console.log('No artifacts found. This might indicate:');
      console.log('1. The repository path is incorrect');
      console.log('2. The repository is empty');
      console.log('3. Permission issues');
      return;
    }
    
    // Show first few artifacts as examples
    console.log('\nFirst 5 artifacts found:');
    for (let i = 0; i < Math.min(5, allArtifacts.length); i++) {
      const artifact = allArtifacts[i];
      console.log(`  ${artifact.groupId}:${artifact.artifactId}:${artifact.version}`);
    }
    
    const foundClasses = [];
    let processedCount = 0;
    
    // Search through each artifact for AuditDomain
    console.log('\nSearching for AuditDomain class...');
    for (const artifact of allArtifacts) {
      processedCount++;
      if (processedCount % 100 === 0) {
        console.log(`Processed ${processedCount}/${allArtifacts.length} artifacts...`);
      }
      
      try {
        const classes = await localRepository.getLocalArtifactClasses(artifact);
        const matchingClasses = classes.filter(cls => 
          cls.className.includes('AuditDomain') || 
          cls.fullName.includes('AuditDomain')
        );
        
        if (matchingClasses.length > 0) {
          console.log(`\nFound AuditDomain class in: ${artifact.groupId}:${artifact.artifactId}:${artifact.version}`);
          
          for (const matchingClass of matchingClasses) {
            console.log(`  Class: ${matchingClass.fullName}`);
            
            // Try to decompile the class
            try {
              const classBytes = await classFinder.getClassSource(matchingClass);
              if (classBytes) {
                console.log('  Decompiling...');
                const decompileResult = await decompiler.decompileClass(classBytes, matchingClass.fullName);
                
                foundClasses.push({
                  className: matchingClass.className,
                  fullName: matchingClass.fullName,
                  packageName: matchingClass.packageName,
                  artifact: {
                    groupId: artifact.groupId,
                    artifactId: artifact.artifactId,
                    version: artifact.version,
                    localPath: artifact.localPath
                  },
                  decompiled: decompileResult.success,
                  source: decompileResult.success ? decompileResult.source : decompileResult.error
                });
                
                if (decompileResult.success) {
                  console.log('  ✅ Decompilation successful!');
                  console.log('  📄 Source code:');
                  console.log('  ' + '='.repeat(80));
                  console.log(decompileResult.source);
                  console.log('  ' + '='.repeat(80));
                } else {
                  console.log('  ❌ Decompilation failed:', decompileResult.error);
                }
              } else {
                console.log('  ❌ Could not extract class bytecode');
              }
            } catch (decompileError) {
              console.error(`  ❌ Error during decompilation: ${decompileError}`);
            }
          }
        }
      } catch (error) {
        // Skip artifacts that can't be processed
        continue;
      }
    }
    
    console.log(`\n📊 Search completed!`);
    console.log(`   Processed: ${processedCount} artifacts`);
    console.log(`   Found: ${foundClasses.length} AuditDomain classes`);
    
    if (foundClasses.length === 0) {
      console.log('\n❌ No AuditDomain classes found in the local repository.');
      console.log('This could mean:');
      console.log('1. The class doesn\'t exist in any of the local artifacts');
      console.log('2. The class name is different (try searching for "Audit" or "Domain")');
      console.log('3. Some JAR files couldn\'t be processed');
    }
    
  } catch (error) {
    console.error('❌ Error during search:', error);
  }
}

testSearchAuditDomain();